package com.iwunu.gateway.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.config.UrlConfig;
import com.iwunu.gateway.entity.CmdIssued;
import com.iwunu.gateway.entity.FLockMember;
import com.iwunu.gateway.entity.FLockUser;
import com.iwunu.gateway.entity.FaceLock;
import com.iwunu.gateway.entity.ImageMongo;
import com.iwunu.gateway.repository.FaceLocMemberRepository;
import com.iwunu.gateway.repository.FaceLockRepository;
import com.iwunu.gateway.service.CmdIssuedMongodbService;
import com.iwunu.gateway.service.FaceLockMemberService;
import com.iwunu.gateway.service.FaceLockService;
import com.iwunu.gateway.service.FlockUserService;
import com.iwunu.gateway.service.ImageMongodbService;
import com.iwunu.gateway.util.StringUtil;
import com.iwunu.gateway.vo.FaceLockVo;
import com.iwunu.gateway.vo.LockUpdateVo;
import com.iwunu.gateway.vo.UserCmdIssuedVo;
import com.iwunu.iot.common.util.HttpClientUtil;

@Service
public class FaceLockServiceImpl implements FaceLockService {
	private static final Logger LOGGER = LoggerFactory.getLogger(FaceLockServiceImpl.class);
	@Autowired
	private FaceLockRepository faceLockRepository;

	@Autowired
	private FaceLocMemberRepository lockmemberRepository;

	@Autowired
	private FlockUserService flockUserService;

	@Autowired
	private FaceLockMemberService faceLockMemberService;

	@Autowired
	private ImageMongodbService imageMongodbService;
	@Resource
	private MongoTemplate mongoTemplate;
	@Autowired
	private CmdIssuedMongodbService cmdIssuedMongodbService;
	@Autowired
	private UrlConfig urlConfig;
	
	@Autowired
	private HttpClintService httpClintService;
	@Override
	public FaceLock getFaceLockByUUID(Long lockId) {
		FaceLock gw = faceLockRepository.selectFaceLockById(lockId);
		return gw;
	}

	public FaceLock getFaceLockByMac(String clientId) {
		FaceLock gw = faceLockRepository.selectFaceLockByMac(clientId);
		return gw;
	}

	@Override
	public String save(FaceLockVo flVo, String ownerId) {
		Map<String,Object> param = new HashMap<String,Object>();
		String uuid = UUID.randomUUID().toString();
		FaceLock fl = new FaceLock();
		String clinetId = flVo.getClientId();
		fl.setCreateTime(new Date());
		fl.setIsDel(false);
		fl.setLocation(flVo.getLocation());
		fl.setClientId(flVo.getClientId());
		fl.setOwnerId(ownerId);
		fl.setType(flVo.getType());
		fl.setName(flVo.getName());
		fl.setMac(flVo.getMac());
		fl.setBleName(flVo.getBleName());
		fl.setAdminPassword(flVo.getAdminPassword());
		fl.setBaseCode(flVo.getBaseCode());
		fl.setUuid(uuid);
		fl.setType(1);
		fl = faceLockRepository.saveAndFlush(fl);
		if (fl != null) {
			FLockMember fm = new FLockMember();
			fm.setCreateTime(new Date());
			fm.setLockClientId(clinetId);
			fm.setLockId(Integer.valueOf(fl.getId().toString()));
			fm.setUserId(Integer.valueOf(ownerId));
			fm.setRole(1);
			fm.setIsDel(false);
			lockmemberRepository.saveAndFlush(fm);
		}
		param.put("lockId", fl.getId()+"");
		param.put("nodeId", uuid);
		param.put("merNo", ownerId);
		param.put("lockType", "11");
		param.put("lockName", flVo.getName());
		param.put("lockAddress", flVo.getLocation());
		param.put("appType","4");
		try {
			JSONObject result =	httpClintService.sendMessage(JSON.toJSONString(param),urlConfig.getRegistUrl());
			System.out.println("result+::::::::::::::bleName::"+result.toString()+";;;;;;;;;;;;;;;;"+flVo.getBleName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return uuid;
	}

	@Override
	public int del(Long lockId, String clientId) {
		cmdIssuedMongodbService.removeCmdByDeviceId(clientId);
		imageMongodbService.removeImageByDeviceId(clientId);
		faceLockMemberService.delByLockId(Integer.parseInt(lockId + ""));
		return faceLockRepository.delByLockId(lockId);
	}

	@Override
	public FaceLock update(FaceLock fl) {
		return faceLockRepository.saveAndFlush(fl);
	}

	@Override
	public FaceLock update(LockUpdateVo fl, Integer lockId) {
		FaceLock flock = this.getFaceLockByUUID(Long.valueOf(lockId));
		if (!StringUtils.isBlank(fl.getAdminPassword())) {
			flock.setAdminPassword(fl.getAdminPassword());
		}
		if (!StringUtils.isBlank(fl.getMac())) {
			flock.setMac(fl.getMac());
		}
		if (!StringUtils.isBlank(fl.getName())) {
			flock.setName(fl.getName());
		}
		if (!StringUtils.isBlank(fl.getLocation())) {
			flock.setLocation(fl.getLocation());
		}
		return faceLockRepository.saveAndFlush(flock);
	}

	@Override
	public List<UserCmdIssuedVo> getUserCmdIssude(Map<String, Object> fl, Integer type) {
		List<UserCmdIssuedVo> userCmdIssueds = new ArrayList<UserCmdIssuedVo>();
		Integer userId = Integer.valueOf(fl.get("userId").toString());
		Integer lockId = Integer.valueOf(fl.get("lockId").toString());
		String clientId = fl.get("lockClientId").toString();
		if (fl.get("role").equals(1)) {
			if (type == 7) {
				UserCmdIssuedVo adminCmdIssuedVo = new UserCmdIssuedVo();
				adminCmdIssuedVo.setAvatar(fl.get("avatar") != null ? fl.get("avatar").toString() : "");
				adminCmdIssuedVo.setNickName(fl.get("nickName") != null ? fl.get("nickName").toString() : "");
				adminCmdIssuedVo.setPitNum(101);
				adminCmdIssuedVo.setUserId(fl.get("userId").toString());
				adminCmdIssuedVo.setEndTime("超级管理密码");
				adminCmdIssuedVo.setStartTime(fl.get("createTime").toString());
				adminCmdIssuedVo.setData(fl.get("adminPassword").toString());
				adminCmdIssuedVo.setValid(true);
				adminCmdIssuedVo.setSucc(true);
				adminCmdIssuedVo.setDisable(false);
				adminCmdIssuedVo.setAdminPwd(false);
				userCmdIssueds.add(adminCmdIssuedVo);
			}
			List<Map<String, Object>> members = lockmemberRepository.selectFaceLockMembers(lockId);
			List<CmdIssued> cmdIssueds = cmdIssuedMongodbService.getSendCmd(clientId, type);
			for (CmdIssued cmdIssued : cmdIssueds) {
				for (Map<String, Object> map : members) {
					if (!map.get("userId").toString().equals(cmdIssued.getUserId()))
						continue;
					UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
					userCmdIssuedVo.setAvatar(map.get("avatar") != null ? map.get("avatar").toString() : "");
					userCmdIssuedVo.setNickName(StringUtils.isNotBlank(cmdIssued.getRemark()) ? cmdIssued.getRemark()
							: map.get("nickName").toString());
					userCmdIssuedVo.setPitNum(cmdIssued.getPitNum());
					userCmdIssuedVo.setUserId(cmdIssued.getUserId());
					userCmdIssuedVo.setEndTime(cmdIssued.getEndTime());
					userCmdIssuedVo.setStartTime(cmdIssued.getStartTime());
					userCmdIssuedVo.setData(
							fl.get("userId").toString().equals(map.get("userId").toString()) ? cmdIssued.getData()
									: StringUtil.replaceof(cmdIssued.getData()));
					userCmdIssuedVo.setValid(cmdIssued.isValid());
					userCmdIssuedVo.setSucc(cmdIssued.isSucc());
					userCmdIssuedVo.setDisable(map.get("role").equals(1) ? false : true);
					userCmdIssuedVo.setAdminPwd(false);
					LOGGER.debug(map.get("userId") + ":" + cmdIssued.getUserId() + ":userCmdIssuedVo:"
							+ JSONObject.toJSONString(userCmdIssuedVo));
					userCmdIssueds.add(userCmdIssuedVo);
				}
			}
			return userCmdIssueds;
		}
		if (fl.get("role").equals(2)) {
			List<Map<String, Object>> members = lockmemberRepository.selectFaceLockMembers(lockId);
			List<CmdIssued> cmdIssueds = cmdIssuedMongodbService.getSendCmd(clientId, type);
			for (CmdIssued cmdIssued : cmdIssueds) {
				for (Map<String, Object> map : members) {
					if (!map.get("userId").toString().equals(cmdIssued.getUserId()))
						continue;
					UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
					userCmdIssuedVo.setAvatar(map.get("avatar") != null ? map.get("avatar").toString() : "");
					userCmdIssuedVo.setNickName(StringUtils.isNotBlank(cmdIssued.getRemark()) ? cmdIssued.getRemark()
							: map.get("nickName").toString());
					userCmdIssuedVo.setPitNum(cmdIssued.getPitNum());
					userCmdIssuedVo.setUserId(cmdIssued.getUserId());
					userCmdIssuedVo.setEndTime(cmdIssued.getEndTime());
					userCmdIssuedVo.setStartTime(cmdIssued.getStartTime());
					userCmdIssuedVo.setData(
							fl.get("userId").toString().equals(map.get("userId").toString()) ? cmdIssued.getData()
									: StringUtil.replaceof(cmdIssued.getData()));
					userCmdIssuedVo.setValid(cmdIssued.isValid());
					userCmdIssuedVo.setSucc(cmdIssued.isSucc());
					userCmdIssuedVo.setDisable(false);
					userCmdIssuedVo.setAdminPwd(false);
					userCmdIssueds.add(userCmdIssuedVo);
				}
			}
			return userCmdIssueds;
		} else {
			FLockUser fu = flockUserService.getFlackUserByUserId(Long.valueOf(userId));
			List<CmdIssued> cmdIssueds = cmdIssuedMongodbService.getUserSendCmd(userId, clientId, type);
			for (CmdIssued cmdIssued : cmdIssueds) {
				UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
				userCmdIssuedVo.setAvatar(fu.getAvatar() != null ? fu.getAvatar() : "");
				userCmdIssuedVo.setNickName(fu.getNickName() != null ? fu.getNickName() : "");
				userCmdIssuedVo.setNickName(
						StringUtils.isNotBlank(cmdIssued.getRemark()) ? cmdIssued.getRemark() : fu.getNickName());
				userCmdIssuedVo.setPitNum(cmdIssued.getPitNum());
				userCmdIssuedVo.setUserId(cmdIssued.getUserId());
				userCmdIssuedVo.setEndTime(cmdIssued.getEndTime());
				userCmdIssuedVo.setStartTime(cmdIssued.getStartTime());
				userCmdIssuedVo.setData(cmdIssued.getData());
				userCmdIssuedVo.setValid(cmdIssued.isValid());
				userCmdIssuedVo.setSucc(cmdIssued.isSucc());
				userCmdIssuedVo.setAdminPwd(false);
				userCmdIssueds.add(userCmdIssuedVo);
			}
			return userCmdIssueds;
		}

	}

	public List<UserCmdIssuedVo> getUserImageData(Map<String, Object> fl) {
		List<UserCmdIssuedVo> userCmdIssueds = new ArrayList<UserCmdIssuedVo>();
		Integer userId = Integer.valueOf(fl.get("userId").toString());
		String clientId = fl.get("lockClientId").toString();
		if (fl.get("role").equals(1)) {
			List<ImageMongo> imageDatas = imageMongodbService.getSendImageData(clientId);
			for (ImageMongo imageMongo : imageDatas) {
				UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
				userCmdIssuedVo.setAvatar(imageMongo.getImageUrl());
				userCmdIssuedVo.setNickName(imageMongo.getRemark());
				userCmdIssuedVo.setPitNum(imageMongo.getPitNum());
				userCmdIssuedVo.setUserId(imageMongo.getUserId());
				userCmdIssuedVo.setEndTime(imageMongo.getEndTime());
				userCmdIssuedVo.setStartTime(imageMongo.getStartTime());
				userCmdIssuedVo.setValid(imageMongo.isValid());
				userCmdIssuedVo.setSucc(imageMongo.isSucc());
				userCmdIssuedVo.setData("");
				userCmdIssueds.add(userCmdIssuedVo);
			}
			return userCmdIssueds;
		} else if (fl.get("role").equals(2)) {
			List<ImageMongo> imageDatas = imageMongodbService.getUserSendImageData(userId, clientId);
			List<ImageMongo> others = imageMongodbService.getSendImageDataByRole(3, clientId);
			for (ImageMongo imageMongo : imageDatas) {
				UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
				userCmdIssuedVo.setAvatar(fl.get("avatar") != null ? fl.get("avatar").toString() : "");
				userCmdIssuedVo.setNickName(imageMongo.getRemark());
				userCmdIssuedVo.setPitNum(imageMongo.getPitNum());
				userCmdIssuedVo.setUserId(imageMongo.getUserId());
				userCmdIssuedVo.setEndTime(imageMongo.getEndTime());
				userCmdIssuedVo.setStartTime(imageMongo.getStartTime());
				userCmdIssuedVo.setValid(imageMongo.isValid());
				userCmdIssuedVo.setData("");
				userCmdIssuedVo.setSucc(imageMongo.isSucc());
				userCmdIssuedVo.setDisable(fl.get("role").equals(1) ? false : true);
				userCmdIssueds.add(userCmdIssuedVo);
			}
			for (ImageMongo imageMongo : others) {
				UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
				userCmdIssuedVo.setAvatar(imageMongo.getImageUrl());
				userCmdIssuedVo.setNickName(imageMongo.getRemark());
				userCmdIssuedVo.setPitNum(imageMongo.getPitNum());
				userCmdIssuedVo.setUserId(imageMongo.getUserId());
				userCmdIssuedVo.setEndTime(imageMongo.getEndTime());
				userCmdIssuedVo.setStartTime(imageMongo.getStartTime());
				userCmdIssuedVo.setValid(imageMongo.isValid());
				userCmdIssuedVo.setData("");
				userCmdIssuedVo.setSucc(imageMongo.isSucc());
				userCmdIssueds.add(userCmdIssuedVo);
//					 }
			}
			return userCmdIssueds;
		} else {
			List<ImageMongo> imageDatas = imageMongodbService.getUserSendImageData(userId, clientId);
			for (ImageMongo imageMongo : imageDatas) {
				UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
				userCmdIssuedVo.setAvatar(imageMongo.getImageUrl());
				userCmdIssuedVo.setNickName(imageMongo.getRemark());
				userCmdIssuedVo.setPitNum(imageMongo.getPitNum());
				userCmdIssuedVo.setUserId(imageMongo.getUserId());
				userCmdIssuedVo.setEndTime(imageMongo.getEndTime());
				userCmdIssuedVo.setValid(imageMongo.isValid());
				userCmdIssuedVo.setStartTime(imageMongo.getStartTime());
				userCmdIssuedVo.setSucc(imageMongo.isSucc());
				userCmdIssuedVo.setData("");
				userCmdIssueds.add(userCmdIssuedVo);
			}
			return userCmdIssueds;
		}

	}

	/**
	 * 管理平台获取所有下发人脸数据
	 * 
	 */
	public Map<String, Object> getAdminImageData(String clientId, Integer currentPage, Integer pageSize, String name) {
		List<UserCmdIssuedVo> userCmdIssueds = new ArrayList<UserCmdIssuedVo>();
		Map<String, Object> resultMap = new HashMap<>();
		Query query = new Query();
		// 当前页码 默认给了0
		pageSize = pageSize != 0 ? pageSize : 10;
		// 页面展示数据条数 默认给了 10
		currentPage = currentPage != null ? currentPage : 1;
		// 筛选条件
		query.addCriteria(Criteria.where("clientId").is(clientId));
		// 设置起始数 // 设置查询条数
		query.skip((currentPage - 1) * pageSize).limit(pageSize);
		long totalCount = mongoTemplate.count(query, CmdIssued.class);
		// 数据总页数
		int totalPage = (int) (totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1);
		// 设置记录总数和总页数
		resultMap.put("totalCount", totalCount);
		resultMap.put("totalPage", totalPage);
		// 动态拼接查询条件
		if (StringUtils.isNotBlank(name)) {
			query.addCriteria(Criteria.where("remark").regex(name));
		}
		// 按创建时间倒序
		query.with(new Sort(Sort.Direction.DESC, "pitNum"));
		// 获取总条数
		List<ImageMongo> imageDatas = mongoTemplate.find(query, ImageMongo.class);
		for (ImageMongo imageMongo : imageDatas) {
			UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
			userCmdIssuedVo.setAvatar(this.replaceImageUrl(imageMongo.getImageUrl()));
			userCmdIssuedVo.setNickName(imageMongo.getRemark());
			userCmdIssuedVo.setPitNum(imageMongo.getPitNum());
			userCmdIssuedVo.setUserId(imageMongo.getUserId());
			userCmdIssuedVo.setEndTime(imageMongo.getEndTime());
			userCmdIssuedVo.setStartTime(imageMongo.getStartTime());
			userCmdIssuedVo.setValid(imageMongo.isValid());
			userCmdIssuedVo.setSucc(imageMongo.isSucc());
			userCmdIssuedVo.setData("");
			if ((imageMongo.isValid() && imageMongo.isSucc())
					|| (imageMongo.getStatus() != null && imageMongo.getStatus() == 1)) {
				userCmdIssuedVo.setStatus(1);
			} else if ((imageMongo.isValid() && !imageMongo.isSucc())
					|| (imageMongo.getStatus() != null && imageMongo.getStatus() == 0)) {
				userCmdIssuedVo.setStatus(0);
			} else if ((!imageMongo.isValid() || imageMongo.isSucc())
					|| (imageMongo.getStatus() != null && imageMongo.getStatus() == 3)) {
				userCmdIssuedVo.setStatus(3);
			}
			userCmdIssueds.add(userCmdIssuedVo);
		}
		resultMap.put("currentPage", currentPage);
		resultMap.put("pageSize", pageSize);
		resultMap.put("content", userCmdIssueds);
		return resultMap;
	}

	/**
	 * 管理平台获取所有下发密码/指纹/卡片数据
	 */
	@Override
	public Map<String, Object> getAdminCmdIssude(Long lockId, String clientId, Integer currentPage, Integer pageSize,
			Integer type, String name) {
		Map<String, Object> resultMap = new HashMap<>();
		Query query = new Query();
		// 当前页码 默认给了0
		pageSize = pageSize != 0 ? pageSize : 10;
		// 页面展示数据条数 默认给了 10
		currentPage = currentPage != null ? currentPage : 1;
		// 筛选条件
		query.addCriteria(Criteria.where("clientId").is(lockId).and("type").is(type));
		// 设置起始数 // 设置查询条数
		query.skip((currentPage - 1) * pageSize).limit(pageSize);
		long totalCount = mongoTemplate.count(query, CmdIssued.class);
		// 数据总页数
		int totalPage = (int) (totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1);
		// 设置记录总数和总页数
		resultMap.put("totalCount", totalCount);
		resultMap.put("totalPage", totalPage);
		// 动态拼接查询条件
		if (StringUtils.isNotBlank(name)) {
			query.addCriteria(Criteria.where("name").regex(name));
		}
		// 按创建时间倒序
		query.with(new Sort(Sort.Direction.DESC, "pitNum"));
		// 获取总条数
		List<UserCmdIssuedVo> userCmdIssueds = new ArrayList<UserCmdIssuedVo>();
		if (type != 7) {
			List<Map<String, Object>> members = lockmemberRepository.selectFaceLockMembers(lockId.intValue());
			List<CmdIssued> cmdIssueds = mongoTemplate.find(query, CmdIssued.class);
			for (CmdIssued cmdIssued : cmdIssueds) {
				for (Map<String, Object> map : members) {
					UserCmdIssuedVo userCmdIssuedVo = new UserCmdIssuedVo();
					userCmdIssuedVo.setAvatar(map.get("avatar") != null ? map.get("avatar").toString() : "");
					userCmdIssuedVo.setNickName(StringUtils.isNotBlank(cmdIssued.getRemark()) ? cmdIssued.getRemark()
							: map.get("nickName").toString());
					userCmdIssuedVo.setPitNum(cmdIssued.getPitNum());
					userCmdIssuedVo.setUserId(cmdIssued.getUserId());
					userCmdIssuedVo.setEndTime(cmdIssued.getEndTime());
					userCmdIssuedVo.setStartTime(cmdIssued.getStartTime());
					userCmdIssuedVo.setData(cmdIssued.getData());
					userCmdIssuedVo.setValid(cmdIssued.isValid());
					userCmdIssuedVo.setSucc(cmdIssued.isSucc());
					userCmdIssuedVo.setAdminPwd(false);
					userCmdIssueds.add(userCmdIssuedVo);
				}
			}
		}
		resultMap.put("currentPage", currentPage);
		resultMap.put("pageSize", pageSize);
		resultMap.put("content", userCmdIssueds);
		return resultMap;
	}

	public List<Map<String, Object>> selectRoleMembers(Integer lockId, Integer role) {
		return lockmemberRepository.selectRoleMembers(lockId, role);
	}

	public List<Map<String, Object>> selectMembers(Integer lockId) {
		return lockmemberRepository.selectMembers(lockId);
	}

	private String replaceImageUrl(String url) {
		if (StringUtils.isNoneBlank(url)) {
			return url.replace("//", "/").replace(":/", "://");
		}
		return "";
	}

	public static void main(String[] args) {
		String name = null;
		System.out.println(StringUtils.isNotBlank(name));
	}
}
